/*
 *  anim.c
 *
 */

#include "anim.h"


/**
 * Create a new animation
 */
anim_t* ANIM_create(const char *file, int size, int delay, int alpha) {
	
	anim_t *a = malloc(sizeof(anim_t));
	if(a==NULL) {
		fprintf(stderr, "Couldn't alloc memory : ANIM_create\n");
		return NULL;
	}
	a->images = malloc(size*sizeof(SDL_Surface));
	if(a->images==NULL) {
		fprintf(stderr, "Couldn't alloc memory : ANIM_create\n");
		return NULL;
	}
	a->size = size;
	a->current = 0;
	a->delay = delay;
	a->timer = clock();
	char buffer[64];
	int i;
	for(i=0;i<a->size;i++) {
		sprintf(buffer, "%s%d.bmp", file, i);
		SDL_Surface *image = SDL_LoadBMP(buffer);
		SDL_SetColorKey(image, SDL_SRCCOLORKEY, SDL_MapRGB(image->format, 255, 0, 255));
		SDL_SetAlpha(image, SDL_SRCALPHA, alpha);
		a->images[i] = image;
	}
	return a;
}


/*
 *
 */
void ANIM_Reset(anim_t *a) {
	a->current = 0;
	a->timer = clock();
}


/**
 * Get the current image
 */
SDL_Surface* ANIM_getImage(anim_t *a) {
	int new_time = clock();
	if((new_time-a->timer)>=a->delay)
	{
		a->timer = new_time;
		a->current = a->current + 1;
		if(a->current>=a->size)
			a->current = 0;
	}
	return a->images[a->current];
}




